package com.wx.tnsbasedata.service.impl;

import com.wx.common.service.RedisService;
import com.wx.tnsbasedata.mapper.CityMapper;
import com.wx.tnsbasedata.model.CityModel;
import com.wx.tnsbasedata.model.vo.CityOrderVo;
import com.wx.tnsbasedata.model.vo.CityVo;
import com.wx.tnsbasedata.service.CityService;
import com.wx.utils.PinYinUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 林建权
 * @version 1.0
 * @date 2020/7/24 17:25
 */
@Service
public class CityServiceImpl implements CityService {

    @Resource
    private CityMapper cityMapper;

//    @Autowired
//    private RedisService redisService;

    //类内常用方法封装

    //cityModel 转 cityVo
    private CityVo cm2cv(CityModel cm){
        CityVo cv = new CityVo();
        BeanUtils.copyProperties(cm,cv);
        cv.setValue(cv.getCityName());
        return cv;
    }


    //查询全部城市，以特定格式返回
    @Override
    public CityVo findAll() {
        //查询数据
        List<CityModel> cmList = cityMapper.findAll();
        //数据封装为HashMap<Integer,CityVo>对象
        HashMap<Integer,CityVo> map = new HashMap<>();
        for(CityModel cm:cmList){
            CityVo cv = cm2cv(cm);
            map.put(cv.getId(),cv);
        }
        //组装成单对象，用children连接
        for (Integer id:map.keySet()){
            CityVo cv = map.get(id);
            //组成list集合
            if (cv.getPid()!=0){
                //不是顶级父id，即中国下省市县
                //找到父级城市
                CityVo cv2 = map.get(cv.getPid());
                //父级城市children变量初始化
                if (cv2.getChildren()==null){
                    cv2.setChildren(new ArrayList<>());
                }
                //加为其子级
                cv2.getChildren().add(cv);
            }
        }
        return map.get(1);
    }

    //添加城市
    @Override
    public int insert(CityModel cityModel) {
        return cityMapper.insert(cityModel);
    }

    @Override
    public int update(CityModel cityModel) {
        return cityMapper.update(cityModel);
    }

    @Override
    public int delete(Integer id) {
        return cityMapper.delete(id);
    }

    @Override
    public List<CityOrderVo> findAllOrder() {

        List<CityOrderVo> list = cityMapper.findAllOrder();
        for (CityOrderVo cityOrder:list){
            char first = PinYinUtil.cn2FirstSpell(cityOrder.getCityName()).toUpperCase().charAt(0);
            cityOrder.setFirst(first);
        }

        return list;
    }


}
